package com.beyondsoft.mcms.web;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.roo.addon.web.mvc.controller.finder.RooWebFinder;
import org.springframework.roo.addon.web.mvc.controller.scaffold.RooWebScaffold;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.beyondsoft.mcms.common.CommonServiceImpl;
import com.beyondsoft.mcms.common.CommonUtils;
import com.beyondsoft.mcms.common.Constants;
import com.beyondsoft.mcms.domain.Category;
import com.beyondsoft.mcms.domain.Fee;
import com.beyondsoft.mcms.domain.FeeAmount;
import com.beyondsoft.mcms.domain.Item;
import com.beyondsoft.mcms.domain.MemberInfo;
import com.beyondsoft.mcms.reference.AuthRole;
import com.beyondsoft.mcms.service.FeeService;

@RequestMapping("/fees")
@Controller
@RooWebScaffold(path = "fees", formBackingObject = Fee.class, delete = false)
@RooWebFinder
public class FeeController {

	@Autowired
    FeeService feeService;
	
	@RequestMapping(method = RequestMethod.POST, produces = "text/html")
    public String create(@Valid Fee fee, BindingResult bindingResult, Model uiModel, HttpServletRequest httpServletRequest) {
        
		Date startDate = fee.getPeriodStartDate();
		Date endDate = fee.getPeriodEndDate();
		MemberInfo member = fee.getPayer();
		List<Fee> fees = Fee.findFeesByPayerAndPayStatus(member, null).getResultList();
		for (Iterator<Fee> it=fees.iterator(); it.hasNext();){
			Fee feeExists = it.next();
			if (startDate.compareTo(feeExists.getPeriodStartDate())>=0 
					&& startDate.compareTo(feeExists.getPeriodEndDate())<=0 ){
				
				bindingResult.rejectValue("periodStartDate", null, "期间开始日期已存在或有重叠，请确认后重新输入！");
				populateEditForm(uiModel, fee);
	            return "fees/create";
			}
			if (endDate.compareTo(feeExists.getPeriodStartDate())>=0 
					&& startDate.compareTo(feeExists.getPeriodEndDate())<=0){
				bindingResult.rejectValue("periodEndDate", null, "期间截止日期已存在或有重叠，请确认后重新输入！");
				populateEditForm(uiModel, fee);
	            return "fees/create";
			}
			
			if (startDate.compareTo(new Date())>=0 ){
				bindingResult.rejectValue("periodEndDate", null, "不允许手动创建将来期间的缴费记录，请确认后重新输入！");
				populateEditForm(uiModel, fee);
	            return "fees/create";
			}
			
		}
		
		fee.setCreateDate(new Date());
		fee.setCreatedBy(CommonUtils.getCurrentUsername());
		fee.setPayStatus(Item.findItem(Constants.PAY_STATUS_NOTPAID));
		
        uiModel.asMap().clear();
        feeService.saveFee(fee);
        return "redirect:/fees/" + encodeUrlPathSegment(fee.getId().toString(), httpServletRequest);
    }
    
    @RequestMapping(params = "form", produces = "text/html")
    public String createForm(Model uiModel, HttpServletRequest request) {
    	Fee fee = new Fee();
        populateEditForm(uiModel, fee);
        List<String[]> dependencies = new ArrayList<String[]>();
        if (MemberInfo.countMemberInfoes() == 0) {
            dependencies.add(new String[] { "memberinfo", "memberinfoes" });
            uiModel.addAttribute("dependencies", dependencies);
        }
        
        MemberInfo member = null;
        String memberId = request.getParameter("form");
        if (memberId==null || "".equals(memberId)){
        	member = ((List<MemberInfo>) uiModel.asMap().get("memberinfoes")).get(0);
        	memberId = member.getId().toString();
        }else{
        	member = MemberInfo.findMemberInfo(Long.valueOf(memberId));
        }
        fee.setPayer(member);
        
        FeeAmount feeAmount = FeeAmount.findFeeAmountsByBusinessTypeAndPositionType(
        		member.getBusinessType(), member.getPositionType()).getSingleResult();
        Item feePeriod = feeAmount.getFeePeriod();
        List<Date> datePeriod = new CommonServiceImpl().getPeriodLately(feePeriod);
        fee.setPeriodStartDate(datePeriod.get(0));
        fee.setPeriodEndDate(datePeriod.get(1));
        fee.setAmountToPay(feeAmount.getPayAmount());
        
        return "fees/create";
    }
	
    @RequestMapping(method = RequestMethod.PUT, produces = "text/html")
    public String update(@Valid Fee fee, BindingResult bindingResult, Model uiModel, HttpServletRequest httpServletRequest) {
        /*
    	if (bindingResult.hasErrors()) {
            populateEditForm(uiModel, fee);
            return "fees/update";
        }
        */
    	
    	Fee oldFee = Fee.findFee(fee.getId());
    	fee.setAmountToPay(oldFee.getAmountToPay());
    	fee.setPayer(oldFee.getPayer());
    	fee.setPeriodStartDate(oldFee.getPeriodStartDate());
    	fee.setPeriodEndDate(oldFee.getPeriodEndDate());
    	fee.setCreateDate(oldFee.getCreateDate());
    	fee.setCreatedBy(oldFee.getCreatedBy());
    	fee.setUpdateDate(new Date());
    	fee.setUpdatedBy(CommonUtils.getCurrentUsername());
    	
        uiModel.asMap().clear();
        //feeService.updateFee(fee);
        fee.merge();
        
        return "redirect:/fees/" + encodeUrlPathSegment(fee.getId().toString(), httpServletRequest);
    }
    
    void populateEditForm(Model uiModel, Fee fee) {
        uiModel.addAttribute("fee", fee);
        addDateTimeFormatPatterns(uiModel);
        
        uiModel.addAttribute("memberinfoes", MemberInfo.findAllMemberInfoes());
        List<Item> feeStatuses = Item.findItemsByCategoryAndIsValid(Category.findCategory(new Long(Constants.PAY_STATUS)), true).getResultList();
        
        AuthRole authority = CommonUtils.getCurrentRole();
    	if (authority.equals(AuthRole.ADMIN)) {
    		uiModel.addAttribute("feestatuses", feeStatuses);
    	}else{
    		feeStatuses.remove(Item.findItem(Constants.PAY_STATUS_CONFIRMED));
    		uiModel.addAttribute("feestatuses", feeStatuses);
    	}
        
    }

    @RequestMapping(params = { "find=ByPayerAndPayStatus", "form" }, method = RequestMethod.GET)
    public String findFeesByPayerAndPayStatusForm(Model uiModel) {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        request.getSession().setAttribute("payer", null);
        request.getSession().setAttribute("payStatus", null);
        return findFeesByPayerAndPayStatus(null, null, uiModel);
    }

    @RequestMapping(params = "find=ByPayerAndPayStatus", method = RequestMethod.GET)
    public String findFeesByPayerAndPayStatus(@RequestParam(value = "payer", required = false) MemberInfo payer, @RequestParam(value = "payStatus", required = false) Item payStatus, Model uiModel) {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String page = request.getParameter("page");
        String size = request.getParameter("size");
        int sizeNo = size == null ? 10 : Integer.valueOf(size);
        int pageNo = page == null ? 1 : Integer.valueOf(page);
        if (page != null && size != null) {
            payer = (MemberInfo) request.getSession().getAttribute("payer");
            payStatus = (Item) request.getSession().getAttribute("payStatus");
        } else {
            request.getSession().setAttribute("payer", payer);
            request.getSession().setAttribute("payStatus", payStatus);
        }
        uiModel.addAttribute("payStatus", payStatus);
        uiModel.addAttribute("payer", payer);
        return list(pageNo, sizeNo, uiModel);
    }

    @RequestMapping(produces = "text/html")
    public String list(@RequestParam(value = "page", required = false) Integer page, @RequestParam(value = "size", required = false) Integer size, Model uiModel) {
    	
    	AuthRole authority = CommonUtils.getCurrentRole();
    	if (authority.equals(AuthRole.ADMIN)) {
    		uiModel.addAttribute("memberinfoes", MemberInfo.findAllMemberInfoes());
            
    	}else {
    		List<MemberInfo> memberinfoes = new ArrayList<MemberInfo>();
    		memberinfoes.add(CommonUtils.getCurrentMember());
        	uiModel.addAttribute("memberinfoes", memberinfoes);
    	}
    	uiModel.addAttribute("feestatuses", Item.findItemsByCategoryAndIsValid(Category.findCategory(new Long(Constants.PAY_STATUS)), true).getResultList());
        
    	MemberInfo payer = (MemberInfo) uiModel.asMap().get("payer");
        Item payStatus = (Item) uiModel.asMap().get("payStatus");
        int sizeNo = size == null ? 10 : size.intValue();
        final int firstResult = page == null ? 0 : (page.intValue() - 1) * sizeNo;
        float nrOfPages = 0.0f;
        
        List<Fee> fees = new ArrayList<Fee>();
        if (authority.equals(AuthRole.ADMIN)) {
        	fees = Fee.findFeesByPayerAndPayStatus(payer, payStatus).getResultList();
        }else{
        	fees = Fee.findFeesByPayerAndPayStatus(CommonUtils.getCurrentMember(), payStatus).getResultList();
        }
        
        int lastResult = (fees.size() > (sizeNo + firstResult)) ? (sizeNo + firstResult) : fees.size();
        nrOfPages = (float) fees.size() / sizeNo;
        uiModel.addAttribute("maxPages", (int) ((nrOfPages > (int) nrOfPages || nrOfPages == 0.0) ? nrOfPages + 1 : nrOfPages));
        uiModel.addAttribute("fees", fees.subList(firstResult, lastResult));
        uiModel.addAttribute("find", "ByPayerAndPayStatus");
        uiModel.addAttribute("selectQueryIds", (payer == null ? "-1" : payer.getId()) + "," + (payStatus == null ? "-1" : payStatus.getId()));
        
        //only admin role can send payment notice
        if (authority.equals(AuthRole.ADMIN)) {
        	uiModel.addAttribute("nopaid", Item.findItem(Constants.PAY_STATUS_NOTPAID).getName());
        }
        
        addDateTimeFormatPatterns(uiModel);
        return "fees/list";
    }

    @RequestMapping(params = { "find=ByPayerAndPayStatus", "exportFlag=true" }, 
    		produces = {"text/plain", "text/html", "application/vnd.ms-excel" }, method = RequestMethod.GET)
    public String exportFeesByPayerAndFeeTypeAndIsPaid(@RequestParam(value = "payer", required = false) MemberInfo payer, @RequestParam(value = "payStatus", required = false) Item payStatus, Model uiModel, HttpServletRequest request, HttpServletResponse response) {
    	AuthRole authority = CommonUtils.getCurrentRole();
    	if (authority.equals(AuthRole.ORDINARY)) {
    		payer = CommonUtils.getCurrentMember();
    	}
    	
    	uiModel.addAttribute("fees", Fee.findFeesByPayerAndPayStatus(payer, payStatus).getResultList());
    	//response.reset();
    	//response.setContentType("application/msexcel;charset=UTF-8");;
        response.setHeader("Content-Disposition", "attachment;filename=" + encodeUrlPathSegment("付费明细表", request) + ".xls");
        return "fees/exportExcel";
    }

    @RequestMapping(params = "smsIds", method = RequestMethod.GET)
    public String smsSending(Model uiModel, HttpServletRequest request) {
        String ids = request.getParameter("smsIds");
        if (ids == null || ids.length() == 0) {
        	return list(1, 10, uiModel);
        }
        
        if (ids.endsWith(",")) {
        	
            List<Fee> feeList = new ArrayList<Fee>();
            ids = ids.substring(0, ids.length() - 1);
            String[] pks = ids.split(",");
            
            for (int i=0; i<pks.length; i++ ){
            	
        		Fee fee = Fee.findFee(Long.valueOf(pks[i]));
        		feeList.add(fee);
            }
            
            new CommonServiceImpl().sendNotice(feeList);
            uiModel.addAttribute("dialogMessage", "缴费通知邮件和短信已发出！");
        }
        
        return list(1, 10, uiModel);
    }
    
}
